package fr.vincent7894.feedroid.feed.provider.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.xmlpull.v1.XmlPullParser;

import android.os.Handler;

import fr.vincent7894.feedroid.feed.context.FeedContext;
import fr.vincent7894.feedroid.feed.context.impl.RssFeedContext;
import fr.vincent7894.feedroid.feed.pojo.Feed;
import fr.vincent7894.feedroid.feed.pojo.FeedAlias;
import fr.vincent7894.feedroid.feed.pojo.impl.RssFeed;
import fr.vincent7894.feedroid.feed.provider.FeedProvider;
import fr.vincent7894.feedroid.utils.NetworkUtils;
import fr.vincent7894.feedroid.utils.XmlPullParserFactoryUtils;

public class RssFeedProvider implements FeedProvider {

	@Override
	public boolean supports(FeedContext feedContext) {
		return (feedContext instanceof RssFeedContext);
	}

	@Override
	public Collection<Feed> list(FeedAlias feedAlias, Handler handler) {
		InputStream inputStream = null;
		try {
			inputStream = NetworkUtils.httpGet(feedAlias.getUri());
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (inputStream == null) {
			throw new IllegalStateException("InputStream can't be null");
		}
		
		return this.doParseStream(inputStream, handler);
	}

	private Collection<Feed> doParseStream(InputStream inputStream, Handler handler) {
		Collection<Feed> feeds = new ArrayList<Feed>(6);

		XmlPullParser parser = null;
		try {
			parser = XmlPullParserFactoryUtils.newParser();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			RssFeed currentFeed = null;
			while (parser.next() != XmlPullParser.END_DOCUMENT) {
				if (parser.getEventType() == XmlPullParser.START_TAG) {
					if (parser.getName().equals("item")) {
						currentFeed = new RssFeed();
					} else if (parser.getName().equals("title")) {
						currentFeed.setTitle(parser.getText());
					} else if (parser.getName().equals("content")) {
						currentFeed.setContent(parser.getText());
					} else if (parser.getName().equals("link")) {
						currentFeed.setLink(parser.getText());
					} else if (parser.getName().equals("pubDate")) {
						currentFeed.setPubDate(parser.getText());
					}
				} else if (parser.getEventType() == XmlPullParser.END_TAG
						&& parser.getName().equals("item")) {
					feeds.add(currentFeed);
					currentFeed = null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return feeds;
	}
}
